package com.yunfei.common.auto.cratePage;



import com.yunfei.common.auto.GeneratorBase;
import com.yunfei.common.auto.util.CapitalizeUtil;
import com.yunfei.common.auto.util.DbInfoUtil;
import com.yunfei.utils.string.StringUtil;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.List;
import java.util.Map;

/**
 * 自动创建表单页面
 * @author  贤云
 *
 */
public class GeneratorFormPage extends GeneratorBase {
    public static Connection getConnection(){
        Connection conn = null;
        try {
            Class.forName(GeneratorBase.DRIVER);
            String url = GeneratorBase.URL;
            String user = GeneratorBase.NAME;
            String pass = GeneratorBase.PASS;
            conn = DriverManager.getConnection(url,user,pass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static void main(String[] args){
        GeneratorFormPage generatorInitPageDB=new GeneratorFormPage();
        generatorInitPageDB.generatorInitPage();
    }
    public  void generatorInitPage(){
        boolean whetherCreateUploadJs=false;
        Connection conn=getConnection();
        String sql="select * from "+tablename;
        PreparedStatement stmt;
        String content="";
        try {
            stmt = conn.prepareStatement(sql);
            ResultSet rs=stmt.executeQuery(sql);
            //ResultSetMetaData data=rs.getMetaData();
            String driver = GeneratorBase.DRIVER;
            String url = GeneratorBase.URL;
            String user = GeneratorBase.NAME;
            String pwd =GeneratorBase.PASS;
            //String table = "FZ_USER_T";
            GeneratorBase generatorBase=new GeneratorBase();
            String table = generatorBase.tablename;
            List<Map<String,Object>> data= DbInfoUtil.getTableInfo(driver,url,user,pwd,table);
            DatabaseMetaData dbmd=conn.getMetaData();
            ResultSet  resultSet  = dbmd.getTables(null, "%", tablename, new String[] { "TABLE" });

            while(rs.next()){
                int columnCount=data.size();
                for(int i = 1 ; i<columnCount ; i++){
                    //获得所有列的数目及实际列数
                    //获得指定列的列名
                    String columnName = data.get(i).get("COLUMN_NAME").toString();
                    String columnRemark=data.get(i).get("columnRemark").toString();
                    String columnRemarkAll=columnRemark;
                    //获得指定列的列值
                    String columnValue = rs.getString(i);
                    String columnDisplaySize=data.get(i).get("maxlength").toString();
                    String columnLabel= CapitalizeUtil.initcap(columnName.toLowerCase());

                    //是否为空
                    int isNullable=Integer.parseInt(data.get(i).get("isNullable").toString());
                    boolean isFormElement=true;

                    int startIndex=columnRemarkAll.indexOf("<label>");
                    int lastIndex=columnRemarkAll.indexOf("</label>");
                    String noteLabel="";
                    if(lastIndex>0){
                         noteLabel=columnRemarkAll.substring(startIndex+7,lastIndex);//获取元素说明文字
                    }

                    isFormElement = !columnRemarkAll.contains("noFormElement");
                    if(isFormElement){
                        boolean isNullableBoolean=false;
                        if(isNullable==1){
                            isNullableBoolean=true;
                        }
                        if(!content.contains("id=\"" + columnLabel + "\"")&&!columnRemarkAll.contains("isImage")) {//非图片的内容处理
                            content += "\t\t\t\t\t\t<tr>\n" +
                                    "\t\t\t\t\t\t\t<td height=\"35\" width=\"15%\"  align=\"right\" style=\"padding-right: 5px;\" nowrap=\"nowrap\">\n";
                            content+="\t\t\t\t\t\t\t\t<span class=\"dye\" >"+columnRemark+"：";
                            if (!isNullableBoolean){
                                content+= "<font color=\"#ff0000\">*</font>\n";
                            }
                            content+="\t\t\t\t\t\t\t\t</span>\n" +
                                    "\t\t\t\t\t\t\t</td>\n" +
                                    "\t\t\t\t\t\t\t<td width=\"85%\">\n";
                                    //处理有时间框的
                                    if(columnLabel.contains("createTime")){
                                        if(isNullableBoolean){
                                            content+="\t\t\t\t\t\t\t\t<input type=\"text\" style=\"width:400px\" title=\""+columnRemark+"\" id=\""+columnLabel+"\" only=\"true\" name=\""+columnLabel+"\" maxlength=\""+columnDisplaySize+"\"   value=\"${bo."+columnLabel+"}\"   onfocus=\"WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',alwaysUseStartDate:true})\" class=\"Wdate\" />\n" ;
                                        }else{
                                            content+="\t\t\t\t\t\t\t\t<input type=\"text\" style=\"width:400px\" title=\""+columnRemark+"\" id=\""+columnLabel+"\" only=\"true\" name=\""+columnLabel+"\" maxlength=\""+columnDisplaySize+"\"  required=\""+isNullableBoolean+"\" value=\"${bo."+columnLabel+"}\"   onfocus=\"WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',alwaysUseStartDate:true})\" class=\"Wdate\" />\n" ;

                                        }
                                    }else{
                                        if(isNullableBoolean){
                                            content+="\t\t\t\t\t\t\t\t<input type=\"text\" style=\"width:400px\" title=\""+columnRemark+"\" id=\""+columnLabel+"\" only=\"true\" name=\""+columnLabel+"\" maxlength=\""+columnDisplaySize+"\"   class=\"inputWidth\" value=\"${bo."+columnLabel+"}\"/>\n" ;
                                        }else{
                                            content+="\t\t\t\t\t\t\t\t<input type=\"text\" style=\"width:400px\" title=\""+columnRemark+"\" id=\""+columnLabel+"\" only=\"true\" name=\""+columnLabel+"\" maxlength=\""+columnDisplaySize+"\"  required=\""+isNullableBoolean+"\" class=\"inputWidth\" value=\"${bo."+columnLabel+"}\"/>\n" ;
                                        }
                                    }
                                    if(columnName.equals("title")){
                                        content+="\t\t\t\t\t\t\t\t<input type=\"hidden\" id=\"orignName\" value=\"${bo.title}\"/>\n";
                                    }
                            content+= "\t\t\t\t\t\t\t</td>\n" +
                                    "\t\t\t\t\t\t</tr>\n";
                        }
                        //有图片的单独处理
                        if(!content.contains("id=\"" + columnLabel + "\"")&&columnRemarkAll.contains("isImage")){//有图片的内容处理
                            content+="\t\t\t\t\t\t<tr>\n" +
                                    "\t\t\t\t\t\t\t<td height=\"35\" width=\"15%\"  align=\"right\" style=\"padding-right: 5px;\" nowrap=\"nowrap\">\n" +
                                    "\t\t\t\t\t\t\t\t<span class=\"dye\" >"+columnRemark+"：" ;
                                    if (!isNullableBoolean){
                                        content+= "\t\t\t\t\t\t\t\t<font color=\"#ff0000\">*</font>\n";
                                    }
                            content+="</span>\n" +
                                    "\t\t\t\t\t\t\t</td>\n" +
                                    "\t\t\t\t\t\t\t<td width=\"85%\">\n" +
                                    "\t\t\t\t\t\t\t\t<div class=\"site-demo-upload\">\n" +
                                    "\t\t\t\t\t\t\t\t\t<img  src=\"${bo."+columnLabel+"}\"  id=\""+columnLabel+"ImgSrc\" style=\"border: none\">\n" +
                                    "\t\t\t\t\t\t\t\t\t<div class=\"site-demo-upbar\">\n" +
                                    "\t\t\t\t\t\t\t\t\t\t<input type=\"file\" name=\"logoImageFile\"  class=\"layui-upload-file\" id=\""+columnLabel+"ImageUploadId\" data-id=\""+columnLabel+"\">\n" +
                                    "\t\t\t\t\t\t\t\t\t</div>\n" +
                                    "\t\t\t\t\t\t\t\t</div>\n" ;
                                    content+="\t\t\t\t\t\t\t\t<input type=\"hidden\" title=\""+columnRemark+"\" name=\""+columnLabel+"\"  class=\"inputWidth\" value=\"${bo."+columnLabel+"}\" id=\""+columnLabel+"\"/>\n" ;
                                   if(!StringUtil.isNullOrEmpty(noteLabel)){
                                       content+="\t\t\t\t\t\t\t\t<font style=\"color: grey\">"+noteLabel+"</font>\n";
                                   }
                            content+="\t\t\t\t\t\t\t</td>\n" +
                                    "\t\t\t\t\t\t</tr>\n";
                        }
                        if(columnLabel.contains("pic")){
                            whetherCreateUploadJs=true;
                        }
                        //时间框单独处理
                    }
                }
            }
            /****************************************自动生成form.jsp页面 start******************************************************************************/

            try {
                if(whetherCreateUploadJs){
                    //创建上传文件的js文件
                    GeneratorUploadJs generatorUploadJs=new GeneratorUploadJs();
                    generatorUploadJs.generatorInitPage();
                }
                String controllMapId=CapitalizeUtil.replaceUnderlineAndfirstToUpper(this.tablename.toLowerCase(),"_","");
                content=getInitPageContent(pageTitle, pageOutPath,content,controllMapId);
                File directory = new File("");
                String outputPath = directory.getAbsolutePath()+ "/web/"+ pageOutPath+"/form.jsp";
                File file=new File(outputPath);
                file.getParentFile().mkdirs();
                FileWriter fw = new FileWriter(outputPath);
                PrintWriter pw = new PrintWriter(fw);
                pw.println(content);
                pw.flush();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            /****************************************自动生成init.jsp页面 end******************************************************************************/
        } catch (SQLException e) {
            System.out.println("数据库连接失败");
        }
    }
    public static String parse(String all) {
        String comment = null;
        int index = all.indexOf("COMMENT='");
        if(index < 0) {
            return "";
        }
        comment = all.substring(index+9);
        comment = comment.substring(0,comment.length() - 1);
        return comment;
    }
    /**
     *生成表单提交页面
     * @param title 页面标题
     * @param path s9/v3/pastInvestmentCase 页面所在路径
     * @return
     */
    public static  String getInitPageContent(String title,String path,String autoCreateForm,String controlMapID){
        String content="";
        content="<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n" +
                "<%@ page language=\"java\" contentType=\"text/html;charset=utf-8\"\tpageEncoding=\"utf-8\"%>\n" +
                "<%@taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\" %>\n" +
                "<%\n" +
                "String path = request.getContextPath();\n" +
                "String basePath = request.getScheme()+\"://\"+request.getServerName()+\":\"+request.getServerPort()+path+\"/\";\n" +
                "%>\n" +
                "<html>\n" +
                "\t<head>\n" +
                "\t\t<title>"+title+"</title>\n" +
                "\t\t<!-- 引用本页面JS、CSS样式静态资源 -->\n" +
                "\t\t<!--图片上传-->\n" +
                "\t\t<link  rel=\"stylesheet\" type=\"text/css\"  href=\"<%=basePath%>/s9/res/js/layui/css/global.css\"/>\n" +
                "\t\t<link  rel=\"stylesheet\" type=\"text/css\"  href=\"<%=basePath%>/s9/res/js/layui/css/layui.css\"/>\n" +
                "\t\t<link  rel=\"stylesheet\" type=\"text/css\" href=\"<%=basePath%>/s9/res/js/calendar/skin/WdatePicker.css\">\n"+
                "\t\t<%@include file=\"/s9/common/common.jsp\"%>\n" +
                "\t\t<script type=\"text/javascript\"  src=\"<%=basePath%>/s9/res/js/calendar/WdatePicker.js\"></script>\n "+
                "\t\t<script type=\"text/javascript\" src=\"<%=basePath %>/"+path+"/js/form.js?v=${version}\"></script>\n" +
                "\t\t<script type=\"text/javascript\"  src=\"<%=basePath%>/s9/res/js/util/validate.js?v=${version}\"></script>\n" +
                "\t\t<script src=\"<%=basePath%>/s9/res/js/layui/layui.js\" type=\"text/javascript\"></script>\n" +
                "\t\t<script type=\"text/javascript\" src=\"<%=basePath %>/"+path+"/js/upload.js?v=${version}\"></script>\n" +
                "\t</head>\n" +
                "\n" +
                "\t<body class=\"dialogBody\" style=\"overflow-x:hidden\">\n" +
                "\t<form id=\"myForm\" method=\"post\" class=\"layui-form\" action=\"../"+controlMapID+"/save.shtml\" >\n" +
                "\t\t<div class=\"z-legend\" style=\"width:100%\">\n" +
                "\t\t\t<b><font color='#990066' style=\"display: block\">基本信息</font></b>\n" +
                "\t\t</div>\n" +
                "     \t<input type='hidden' name='createPeople' id='createPeople' value='${user.userName}'/>\n" +
                "     \t<input type='hidden' name='id' id='id' value='${bo.id }'/>\n" +
                "\t\t\t<table width=\"100%\" id=\"tableBaseInfo\"  align=\"center\" cellpadding=\"2\" cellspacing=\"0\" style=\"border-collapse:separate; border-spacing:0px 10px;\">\n";
                content+=autoCreateForm;
                content+="\n\t\t\t</table>\n" +
                "\n" +
                "\t\t</form>\n" +
                "\n" +
                "\t<div class=\"layui-form-item\" style=\"padding-left:15%\">\n" +
                "\t\t<div class=\"layui-input-block\">\n" +
                "\t\t\t<a class=\"layui-btn layui-btn-big\" id=\"saveBtn\" lay-filter=\"demo1\">&nbsp;&nbsp;保存&nbsp;&nbsp;</a>\n" +
                "\t\t</div>\n" +
                "\t</div>\n" +
                "\n" +
                "\n" +
                "\n" +
                "\t</body>\n" +
                "</html>\n" +
                "\n" +
                "<script type=\"text/javascript\">\n" +
                "    $(document).ready(function ()\n" +
                "    {\n" +
                "        layui.use('form', function(){\n" +
                "            var form = layui.form(); //只有执行了这一步，部分表单元素才会修饰成功\n" +
                "        });\n" +
                "        //确定按钮\n" +
                "        $(\"#saveBtn\").bind('click',function(){\n" +
                "            if(validate()) {\n" +
                "                repeat();\n" +
                "            }\n" +
                "        });\n" +
                "\n" +
                "\t});\n" +
                "    function forSubmit(){\n" +
                "        var url = $(\"#myForm\").attr('action');\n" +
                "        var data = $(\"#myForm\").serialize();\n" +
                "        $.ajax({\n" +
                "            url: url,\n" +
                "            data: data,\n" +
                "            dataType: 'json',\n" +
                "            type: 'post',\n" +
                "            success: function (data) {\n" +
                "                if (data.result) {\n" +
                "                   parent.reload(\"操作成功\");\n" +
                "                }\n" +
                "            }, error: function () {\n" +
                "                $.ligerDialog.error(\"操作失败\");\n" +
                "            }\n" +
                "        });\n" +
                "\t}\n" +
                "    /**\n" +
                "     * 重复性判断校验\n" +
                "     * */\n" +
                "    function repeat(){\n" +
                "        var only=$(\"#title\").attr('name');\n" +
                "        var name=$(\"#title\").val();\n" +
                "        var orignName=$(\"#orignName\").val();\n" +
                "        var flag=!isNull(name)&&(name!=orignName);\n" +
                "        if(only=='true'&&flag){\n" +
                "            var url=\"../"+controlMapID+"/repeat.shtml\";\n" +
                "            var data={\"name\":name};\n" +
                "            $.ajax({\n" +
                "                url: url,\n" +
                "                data: data,\n" +
                "                dataType: 'json',\n" +
                "                type: 'post',\n" +
                "                success: function (res) {\n" +
                "                    if (res.result) {\n" +
                "                        $.ligerDialog.error(\"名称已经存在,请不要重复添加\");\n" +
                "                    }else{\n" +
                "                        forSubmit();\n" +
                "                    }\n" +
                "                }, error: function () {\n" +
                "                    $.ligerDialog.error(\"操作失败\");\n" +
                "                }\n" +
                "            });\n" +
                "        }else{\n" +
                "            forSubmit();//姓名未做更改，不必须验证重复性\n" +
                "        }\n" +
                "\n" +
                "    }\n" +
                "\n" +
                "</script>\n" +
                "<script>\n" +
                "\n" +
                "\n" +
                "</script>";
        return content;
    }

}
